package shitoumizhen;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.*;

import static java.lang.System.exit;

//自定义窗口类，展示主窗口
//独立的功能独立成方法
public class MainFrame extends JFrame
{
    private static String ImagePath="stone-maze/src/image/";
    private int sum=0;

    private int row;//0的行索引
    private int col;//0的列索引
    private int historyLeastPath=readDate();

    private static int [][]ImageDate=
            {
                    {1,2,3,4},
                    {5,6,7,8},
                    {9,10,11,12},
                    {13,14,15,0}
            };
    private static int [][]WinDate=
            {
                    {1,2,3,4},
                    {5,6,7,8},
                    {9,10,11,12},
                    {13,14,15,0}
            };



    public MainFrame()
    {
     InitFrame();
     InitRandomArray();//先打乱数组，然后初始化图片的时候遍历数组元素的时候就不会是顺序了。可能第一个元素是3.那么初始话的时候就是第三张图片
     InitImage();
     InitMenu();

     InitKeyPressevent();//异步执行，InitKeyPressevent() 方法添加了一个键盘监听器，但这个监听器不会立即执行任何代码；它只是注册了一个事件监听器，等待用户按键事件的发生。键盘监听器的事件处理是异步的，只有在用户按下键时才会触发，不会阻塞构造函数的执行。

        this.setVisible(true);
     }
     public void updateHistoryPath()
     {

         try(
                 Writer wr = new FileWriter("stone-maze\\src\\shitoumizhen\\历史最小步数文档.txt");//覆盖
                 BufferedWriter bw = new BufferedWriter(wr);
             )
         {         bw.write(this.sum+"");


         } catch (IOException e) {
             throw new RuntimeException(e);
         }

     }
    public int readDate()
    {
        try( FileReader re=new FileReader("stone-maze\\src\\shitoumizhen\\历史最小步数文档.txt");
             BufferedReader br = new BufferedReader(re);
        )
        {
            return Integer.parseInt(br.readLine());
        }
        catch (Exception e)
        {
            e.printStackTrace();
            System.out.println("捕捉异常");
            throw new RuntimeException("读取历史最小步数文档失败");
        }

    }

     public boolean checkWin()
     {
         for(int i=0;i<ImageDate.length;i++)
         {
             for(int j=0;j<ImageDate[i].length;j++)
             {
                if(ImageDate[i][j]!=WinDate[i][j])return false;
             }
         }
         return true;
     }
     public void swap(int [][]array,int i1,int j1,int i2,int j2)
     {
         int temp;
         temp=array[i1][j1];
         array[i1][j1]=array[i2][j2];
         array[i2][j2]=temp;
     }
    public void InitKeyPressevent()
    {
        this.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
               switch (e.getKeyCode())
               {
                   case KeyEvent.VK_UP:
                       SwitchandMove (Direction.UP);
                       break;
                   case KeyEvent.VK_DOWN:
                       SwitchandMove (Direction.DOWN);
                       break;
                   case KeyEvent.VK_LEFT:
                       SwitchandMove (Direction.LEFT);
                       break;
                   case KeyEvent.VK_RIGHT:
                       SwitchandMove (Direction.RIGHT);
                       break;

               }

            }
        });
    }

    public void SwitchandMove(Direction direction)
    {
         switch (direction)
         {
             case UP:
                // System.out.println("上");

                 if(row!=3)
                 {
                     swap(ImageDate,row,col,row+1,col);
                     row++;//更新白色快的位置！
                     sum++;

                 }
               //  else JOptionPane.showMessageDialog(this,"无法交换");

                 break;
             case DOWN:
                // System.out.println("下");
                if(row!=0)
                {
                    swap(ImageDate,row,col,row-1,col);
                    row--;
                    sum++;
                }
              //  else JOptionPane.showMessageDialog(this,"无法交换");

                 break;
             case LEFT:
                 //System.out.println("左");

                if(col!=3)
                {
                    swap(ImageDate,row,col,row,col+1);
                    col++;
                     sum++;

                }
               // else JOptionPane.showMessageDialog(this,"无法交换");
                 break;
             case RIGHT:
                 //System.out.println("右");
                if(col!=0)
                {
                    swap(ImageDate,row,col,row,col-1);
                    col--;
                    sum++;
                }
                //lse JOptionPane.showMessageDialog(this,"无法交换");
                 break;

         }
        InitImage();
    }

    public void InitRandomArray()
           {
                 for(int i=0;i<ImageDate.length;i++)
                 {
                     for(int j=0;j<ImageDate[i].length;j++)
                     {
                                 int i1=(int)(Math.random()*ImageDate.length);
                                 int j1=(int)(Math.random()*ImageDate[i].length);

                                 int i2=(int)(Math.random()*ImageDate.length);
                                 int j2=(int)(Math.random()*ImageDate[i].length);

                                 int temp=ImageDate[i1][j1];

                                 ImageDate[i1][j1]=ImageDate[i2][j2];
                                 ImageDate[i2][j2]=temp;






                                 if(ImageDate[i][j]==0)
                                 {
                                     row=i;
                                     col=j;
                                 }


                     }
                 }
           }

     public void InitMenu()
     {
              JMenuBar menuBar=new JMenuBar();
              JMenu menu=new JMenu("菜单");
              JMenuItem exitJI=new JMenuItem("退出");
              menu.add(exitJI);
              exitJI.addActionListener(new ActionListener()
                                       {
                                           @Override
                                           public void actionPerformed(ActionEvent e) {
                                               MainFrame.this.dispose();
                                           }
                                       }

              );

              JMenuItem restartJI=new JMenuItem("重启");
              restartJI.addActionListener(new ActionListener() {
                  @Override
                  public void actionPerformed(ActionEvent e) {
                   //JOptionPane.showMessageDialog(MainFrame.this,"还没做好");
                // MainFrame.this.dispose();
                  //new MainFrame();
                      InitRandomArray();
                      InitImage();
                  }
              });
              menu.add(restartJI);
              menuBar.add(menu);
              this.setJMenuBar(menuBar);

     }

    private void InitImage()
    {
        //先清除上一层的图层便于刷新新的图层,相当于桌布给你抽了，默认有内容面板（桌布）
        this.getContentPane().removeAll();

        if(checkWin())
        {
            JLabel label4=new JLabel();
            label4.setIcon(new ImageIcon(ImagePath+"win.png"));
            label4.setBounds(124,230,266,88);
            this.add(label4);

            if(this.sum<=this.historyLeastPath)
            {
                updateHistoryPath();
              // System.out.println("数据修改成功");
            }


        }
        //给窗口添加一个展示文字的组件
        JLabel sumTxt=new JLabel("当前移动:"+sum+"步数");
        sumTxt.setBounds(0,0,100,20);
        this.add(sumTxt);

        JLabel HistoryTxt =new JLabel("历史最少胜利步数:"+((this.historyLeastPath==999999999)?"无":(this.historyLeastPath+"")));
        HistoryTxt.setBounds(300,0,800,20);
        this.add(HistoryTxt);

         //展示一个图片的行列矩阵，铺满背景4*4
        for(int i=0;i<ImageDate.length;i++)
        {
            for(int j=0;j<ImageDate[i].length;j++)
           {

            String imageName=ImageDate[i][j]+".png";
            JLabel label2=new JLabel();
            label2.setIcon(new ImageIcon( ImagePath + imageName));
            label2.setBounds(j*100+20,i*100+60,100,100);
               this.add(label2);
           }
        }
           //背景图片的设置
            JLabel label3=new JLabel();
            label3.setIcon(new ImageIcon(ImagePath+"background.png"));
            label3.setBounds(0,0,460,484);
            this.add(label3);

            this.repaint();//刷新图层




    }



     private void InitFrame()
     {
         this.setTitle("石头迷宫");
         this.setSize(465,575);
         this.setLocationRelativeTo(null);
         this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         this.setLayout(null);


        // this.setVisible(true);
     }



}
